//
//  TaskViewController.m
//  Molian
//
//  Created by 胡津 on 15/4/1.
//  Copyright (c) 2015年 xiaocan. All rights reserved.
//

#import "TaskViewController.h"
#import "TaskTableViewCell.h"
#import "MLUserDataViewController.h"

#import "UMSocialControllerService.h"

@interface TaskViewController ()<UITableViewDelegate,UITableViewDataSource,UMSocialUIDelegate>
//视图列表
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, assign)NSInteger taskFriendStatus;
@property (nonatomic, assign)NSInteger taskUserDataStatus;

@end

@implementation TaskViewController
{
    NSArray *titleArr;
    NSArray *detailsArr;
    NSArray *ResultArr;
}
- (void)reloadTableView
{
    //取出本地存储的奖励记录
    NSUserDefaults *uD =   [NSUserDefaults standardUserDefaults];
    NSDictionary *dic = [uD objectForKey:[NSString stringWithFormat:@"%@task",[MLUser currentUser].objectId]];
    int a = 0;
    if(dic){
        //分享记录
        if([dic objectForKey:@"share"]){
            if([[dic objectForKey:@"share"] isEqualToString:@"YES"]){
                a++;
                self.taskFriendStatus = MLTaskStatus_FINISHED;
                [self.tableView reloadData];
            }
        }
        //资料记录
        if([dic objectForKey:@"data"]){
            if([[dic objectForKey:@"data"] isEqualToString:@"YES"]){
                a++;
                self.taskUserDataStatus = MLTaskStatus_FINISHED;
                [self.tableView reloadData];
            }
        }
        
    }
   
    if (a==2) {
        //全部完成奖励不需要检索
    }else{
        AVQuery *query = [MLTask query];
        MLUser *u = [MLUser currentUser];
        [query whereKey:@"user" equalTo:u];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            if (!error) {
                //检索成功
                NSLog(@"%@",objects);
                for (MLTask  *task in objects) {
                    if (task.type == MLTaskType_INVITE_FRIEND) {
                        //  邀请好友
                        if(task.status>=self.taskFriendStatus){
                            
                            if(task.status == MLTaskStatus_FINISHED){
                                
                                [self saveTaskDataKey:@"share"];
                            }
                            
                            
                            self.taskFriendStatus = task.status;
                        }
                    }else if (task.type == MLTaskType_COMPLETE_INFO){
                        //  
                        
                        if(task.status>=self.taskUserDataStatus){
                            if(task.status == MLTaskStatus_FINISHED){
                                [self saveTaskDataKey:@"data"];
                            }
                            self.taskUserDataStatus = task.status;
                            if (task.status == MLTaskStatus_NORMAL ) {
                                [self dataFull];
                                
                            }
                        }
                    }
                }
                
                
                [self.tableView reloadData];
            }else{
                NSLog(@"%@",@"网络异常");
                //检索失败
            }
        }];
    }
}

- (void)saveTaskDataKey:(NSString *)key
{
    NSUserDefaults *uD =   [NSUserDefaults standardUserDefaults];
    NSDictionary *dic = [uD objectForKey:[NSString stringWithFormat:@"%@task",[MLUser currentUser].objectId]];
    NSMutableDictionary *mdic = [NSMutableDictionary dictionaryWithDictionary:dic];
    [mdic setObject:@"YES" forKey:key];
    [uD setObject:mdic forKey:[NSString stringWithFormat:@"%@task",[MLUser currentUser].objectId]];
    [uD synchronize];
    
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self reloadTableView];
    [HUD hideFromViewAnimated:YES];

}
- (void)viewDidLoad {
    [super viewDidLoad];
    [AVAnalytics event:@"奖励页面访问"]; // 通知服务器一个点击事件。

    self.taskFriendStatus = 0;
    self.taskUserDataStatus = 0;
    // Do any additional setup after loading the view.
    self.view.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
    self.title = @"奖励";
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, DeviceHeight)style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = RGBA(244, 244, 244, 1);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollsToTop = YES;
    self.tableView.separatorColor = RGBA(244, 244, 244, 1);//分隔条颜色
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 20, 0);//偏移量
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 51, 0);//滚动条偏移量
    self.tableView.tableHeaderView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"top_renwu_image"]];
    self.tableView.tableFooterView = [[UIView alloc] init];//不显示空的cell
    [self.view addSubview:self.tableView];
    titleArr = @[@"分享应用",@"完善资料"];
    detailsArr = @[@"描述:分享应用给单身汪朋友",@"描述:资料完成度达到100%",@"奖励:5时光",@"奖励:5时光"];
    ResultArr = @[@"去完成",@"领奖励",@"已领取"];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static  NSString *CellIdentifier = @"RecommendCell" ;
    //自定义cell类
    TaskTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if  (cell == nil) {
        cell = [[TaskTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    }
    cell.taskTitleLabel.text = [NSString stringWithFormat:@"%@",titleArr[indexPath.row]];
    //cell.taskDetailsLabel.text = detailsArr[indexPath.row];
    NSString *hiht;
    if (indexPath.row == 0) {
        hiht = detailsArr[2];
    }else{
        hiht = detailsArr[3];
    }
    
    cell.taskDetailsLabel.text = [NSString stringWithFormat:@"%@\n%@",detailsArr[indexPath.row],hiht];
    [cell.taskResultBtn setTitle:ResultArr[indexPath.row==0?self.taskFriendStatus:self.taskUserDataStatus] forState:UIControlStateNormal];
    if ([cell.taskResultBtn.titleLabel.text isEqualToString:@"去完成"]) {
        
        [cell.taskResultBtn setBackgroundColor:RGBA(248, 207, 30, 1)];
    }else if ([cell.taskResultBtn.titleLabel.text isEqualToString:@"领奖励"]){
        [cell.taskResultBtn setBackgroundColor:[UIColor paperColorGreenA200]];
    }else{
        [cell.taskResultBtn setBackgroundColor:RGBA(234, 234, 234, 1)];
    }
    cell.taskResultBtn.tag = 123+indexPath.row;
    [cell.taskResultBtn addTarget:self action:@selector(clickBt:) forControlEvents:UIControlEventTouchUpInside];
    cell.taskResultBtn.userInteractionEnabled = YES;
    cell.backgroundColor = [UIColor clearColor];
    return  cell;
}
- (void)clickBt:(UIButton *)bt
{
    bt.userInteractionEnabled = NO;
    if (bt.tag == 123) {
        //邀请好友
        if([bt.titleLabel.text isEqualToString:@"去完成"]){
            [self Actionshare];
        }else if ([bt.titleLabel.text isEqualToString:@"领奖励"]){
            
            [self getRewardType:MLTaskType_INVITE_FRIEND];
        }
    }else if (bt.tag == 123+1){
        if([bt.titleLabel.text isEqualToString:@"去完成"]){
            //生成奖励记录
            
            MLUserDataViewController *userInfoVC = [[MLUserDataViewController alloc]init];
            userInfoVC.userData = [MLUser currentUser];
            
            [Utils pushTabbarHidden:userInfoVC Selfvc:self];
            AVQuery *query = [MLTask query];
            MLUser *u = [MLUser currentUser];
            [query whereKey:@"user" equalTo:u];
            [query whereKey:@"type" equalTo:[NSNumber numberWithInteger:MLTaskType_COMPLETE_INFO]];
            [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
                
                if (error||objects.count == 0) {
                    MLTask *task = [MLTask object];
                    task.status = MLTaskStatus_NORMAL;
                    task.type = MLTaskType_COMPLETE_INFO;
                    task.user = [MLUser currentUser];
                    [task saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        if(succeeded){
                            [self dataFull];
                        }else{
                            // [HUD Prompt:@"分享失败"];
                        }
                    }];
                }
            }];
            
            
            //先判断资料是否完整
        }else if ([bt.titleLabel.text isEqualToString:@"领奖励"]){
            [self getRewardType:MLTaskType_COMPLETE_INFO];
        }
        //完善资料
        //点击去完成
        //开始判断资料完成度
    }
}
- (BOOL)isNSString:(NSString *)str
{
    if (str&&str.length) {
        return YES;
    }
    return NO;
}
- (BOOL)isNSDate:(NSDate *)date
{
    if (date) {
        return YES;
    }
    return NO;
}
- (BOOL)isNSArray:(NSArray *)arr
{
    if (arr&&arr.count) {
        return YES;
    }
    return NO;
}
//资料完整度

- (void)dataFull
{
    MLUser *u = [MLUser currentUser];
    __block  NSInteger a = 0;
    //个人资料
    //昵称
    [self isNSString:u.nickname]==YES?a++:a;
    [self isNSDate:u.birthday]==YES?a++:a;
     [self isNSString:u.location_city]==YES?a++:a;
    //个人签名
    [self isNSString:u.intro]==YES?a++:a;
     u.isHasVoice==YES?a++:a;
   [self isNSString:u.belong]==YES?a++:a;
    //喜欢
    [self isNSArray:u.like_tags]==YES?a++:a;
    //叫我
     [self isNSArray:u.called_tags]==YES?a++:a;
    //外貌
    [self isNSString:u.figure]==YES?a++:a;
    //职业
    [self isNSString:u.job]==YES?a++:a;
    
    //语言
    [self isNSArray:u.language]==YES?a++:a;

    //特技
    [self isNSArray:u.special]==YES?a++:a;
    //兴趣话题
     [self isNSString:u.interestTopic]==YES?a++:a;
     [self isNSArray:u.want_tags]==YES?a++:a;
     [self isNSArray:u.ideal_tags]==YES?a++:a;
   // [self isNSString:u.like]==YES?a++:a;
    //[self isNSArray:u.call_tags]==YES?a++:a;
   
   
    AVQuery *galleryQuery = [MLGallery query];
    [galleryQuery whereKey:@"belong_to" equalTo:u];
    [galleryQuery includeKey:@"images"];
    [galleryQuery getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
        MLGallery *gallery = (MLGallery *)object;
        //图片集
        if ( gallery.images&& gallery.images.count) {
            a = a+gallery.images.count;
        }
        
        if (a>=23) {
            //已完成
            self.taskUserDataStatus = MLTaskStatus_UNGET;
            [self.tableView reloadData];
        }
    }];
}
- (void)getRewardType:(MLTaskType)Type
{
        [HUD setOnViewWithTitle:@"请求中" animated:YES];
        MLUser *u = [MLUser currentUser];
        AVQuery *uQuery = [MLTask query];
        [uQuery whereKey:@"user" equalTo:u];
        [uQuery whereKey:@"type" equalTo:[NSNumber numberWithInteger:Type]];
        [uQuery getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
            if (error) {
                [HUD hideFromViewAnimated:YES];
            }else{
                MLTask *t = (MLTask *)object;
                if(Type == MLTaskType_COMPLETE_INFO){
                    t.status = MLTaskStatus_FINISHED;
                    [self reloadTableView];
                    self.taskUserDataStatus =  MLTaskStatus_FINISHED;
                    [t saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        if(succeeded){
                            
                            NSDictionary *params = @{@"userId":u.objectId,@"price":[NSNumber numberWithFloat:0.5],@"type":[NSNumber numberWithInteger:INCOME_TYPE_TASK]};
                            [AVCloud callFunctionInBackground:@"modifyBalance"withParameters:params block:^(id object, NSError *error) {
                            }];
                        }
                    }];
                    [HUD hideFromViewAnimated:YES];
                }else{
                    t.status = MLTaskStatus_FINISHED;
                    self.taskFriendStatus =  MLTaskStatus_FINISHED;
                    [self reloadTableView];
                    [t saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        if (succeeded) {
                            NSDictionary *params = @{@"userId":u.objectId,@"price":[NSNumber numberWithFloat:0.5],@"type":[NSNumber numberWithInteger:INCOME_TYPE_TASK]};
                            [AVCloud callFunctionInBackground:@"modifyBalance"withParameters:params block:^(id object, NSError *error) {
                            }];
                            [HUD hideFromViewAnimated:YES];
                        }
                    }];
                    [HUD hideFromViewAnimated:YES];
                }
            }
        }];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        //点击分享 
    }else if (indexPath.row == 1){
        //完善资料
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
//分享
-(void)Actionshare
{
    //如果需要分享回调,请将delegate对象设置self,并实现下面的回调方法
    [UMSocialSnsService handleOpenURL:[NSURL URLWithString:@"http://www.pocketsweet.com/wap"]];
    
    [UMSocialData defaultData].extConfig.wechatSessionData.url = @"http://www.pocketsweet.com/wap";
    [UMSocialData defaultData].extConfig.qqData.url = @"http://www.pocketsweet.com/wap";
    
    [UMSocialData defaultData].extConfig.title = @"口袋恋人——陌生人虚拟恋爱社交APP";
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:UM_KEY
                                      shareText:@"口袋恋人是一款走心、自由的陌生人虚拟恋爱社交APP。在口袋恋人可以免费和陌生人虚拟恋爱,亲爱的快来试试吧"
                                     shareImage:[UIImage imageNamed:@"icon"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToQQ,UMShareToQzone,UMShareToDouban,UMShareToRenren,UMShareToSms,nil]
                                       delegate:self];
    
    //[ShareData shareData].shareTask = YES;//开始监听
   // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(task) name:@"shareTask" object:nil];
    
}
//完成分享奖励
//- (void)task
//{
//    //得到分享到的微博平台名
//    MLTask *task = [MLTask object];
//    task.status = MLTaskStatus_UNGET;
//    task.type = MLTaskType_INVITE_FRIEND;
//    task.user = [MLUser currentUser];
//    [task saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
//        if(succeeded){
//            [HUD Prompt:@"分享成功"];
//            [self reloadTableView];
//        }else{
//             [HUD Prompt:@"分享失败"];
//        }
//    }];
//}
//用户分享或者关闭分享页面的回调方法
-(void)didCloseShakeView
{
    //    [HUD Prompt:@"我们做的不够好?" Content:@"是吗?" Timer:2];
}
//下面得到分享完成的回调
-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    NSLog(@"didFinishGetUMSocialDataInViewController with response is %@",response);
//    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的微博平台名
        MLTask *task = [MLTask object];
        task.status = MLTaskStatus_UNGET;
        task.type = MLTaskType_INVITE_FRIEND;
        task.user = [MLUser currentUser];
        [task saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if(succeeded){
                [HUD Prompt:@"分享成功"];
                [self reloadTableView];
            }else{
                // [HUD Prompt:@"分享失败"];
            }
        }];
    }else{
        //        [HUD Prompt:@"失败" Content:@"分享失败" Timer:2];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return titleArr.count;//Cell个数
}


//设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 110;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if ([self isViewLoaded]&&!self.view.window) {
        self.view = nil;
    }
    // Dispose of any resources that can be recreated.
}

@end
